package com.service;

import com.dao.AuthorDao;
import com.model.Author;
import com.util.DBUtil;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class AuthorService {

    public List<Author> listAuthors(){
        Connection connection = DBUtil.getConnection();
        AuthorDao authorDao = new AuthorDao();
        List<Author> authors = null;

        try {
            authors = authorDao.listAuthors(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        DBUtil.closeResource(connection,null,null);
        return authors;
    }
    public List<Author> searchAuthorByName(String name){
        Connection connection = DBUtil.getConnection();
        AuthorDao authorDao = new AuthorDao();
        List<Author> Authors = null;

        try {
            Authors = authorDao.searchAuthor(connection,name);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        DBUtil.closeResource(connection,null,null);
        return Authors;
    }
    public boolean addAuthor(Author author){
        boolean flag=false;
        Connection connection = DBUtil.getConnection();
        AuthorDao authorDao = new AuthorDao();

        try {
            authorDao.addAuthor(connection, author);
            flag=true;
        } catch (SQLException e) {
            e.printStackTrace();
            flag=false;
        }

        DBUtil.closeResource(connection,null,null);
        return flag;
    }
    public boolean updateAuthor(Author author){
        boolean flag=false;
        Connection connection = DBUtil.getConnection();
        AuthorDao authorDao = new AuthorDao();

        try {
            authorDao.updateAuthor(connection, author);
            flag=true;
        } catch (SQLException e) {
            e.printStackTrace();
            flag=false;
        }

        DBUtil.closeResource(connection,null,null);
        return flag;
    }
    public boolean deleteAuthorById(int id){
        boolean flag=false;
        Connection connection = DBUtil.getConnection();
        AuthorDao authorDao = new AuthorDao();
        try {
            int updateRows = authorDao.deleteAuthorById(connection, id);
            if (updateRows>0){
                flag=true;
            }

        } catch (SQLException e) {
            e.printStackTrace();
            flag=false;
        }

        DBUtil.closeResource(connection,null,null);
        return flag;
    }

}
